package com.lzx.adx.report.support.strategy.media;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.annnotions.MediaType;
import com.lzx.adx.report.constant.MediaChannelConstant;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.model.youku.AdConvInfo;
import com.lzx.adx.report.util.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
@Slf4j
@MediaType(MediaChannelConstant.youku)
public class YouKuCallBackStrategy extends AbstractCallback{
    @Override
    public ResponseEntity callback(ReportDTO reportDTO, AccountDTO accountDTO, String callType, String ts) {
        boolean base = base(reportDTO, accountDTO, callType, ts);
        if(!base){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String eventType = jsonObject.getString(callType);

        Map<String, Object> param = new HashMap<>();
        param.put("event_type", eventType);
        param.put("event_time", ts);
        param.put("track_id", reportDTO.getRequestId());
        param.put("deep_conv", 0);
        param.put("creative_id", reportDTO.getContentId());//必须是数字

        AdConvInfo advConvInfo = new AdConvInfo();
        advConvInfo.setAppKey(jsonObject.getString("appKey"));//需要替换
        advConvInfo.setContent(param);
        advConvInfo.setSignature(SignUtil.sign(advConvInfo.getAppKey(),jsonObject.getString("token"), toStr(advConvInfo.getContent())));

        String paramsData= JSON.toJSONString(advConvInfo);
        log.info("账号id{},请求id{} 给优酷上报回传完整的地址：{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), accountDTO.getSspApiUrl());
        String result = HttpUtil.post(accountDTO.getSspApiUrl(),paramsData );
        log.info("账号id{},请求id{} 给优酷上报回传响应的结果为：{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), result);

        return ResponseEntity.ok(new Result());
    }


    public static String toStr(Map<String, Object> params) {
        if (CollectionUtil.isEmpty(params)) {
            return null;
        }
        List<String> paramNameList = Lists.newArrayList();
        paramNameList.addAll(params.keySet());
        Collections.sort(paramNameList);
        StringBuilder builder = new StringBuilder();
        boolean first = true;
        for (String key : paramNameList) {
            if (first) {
                first = false;
            } else {
                builder.append("&");
            }
            builder.append(key).append("=");
            Object value = params.get(key);
            String valueString = "";
            if (null != value) {
                valueString = String.valueOf(value);
            }
            builder.append(valueString);
        }
        return builder.toString();
    }
}
